package com.yqg.education.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yqg.education.common.Result;
import com.yqg.education.common.interceptor.SysLog;
import com.yqg.education.controller.dto.StuDTO;
import com.yqg.education.controller.dto.UserDTO;
import com.yqg.education.controller.dto.UserPasswordDTO;
import com.yqg.education.entity.ClassStudent;
import com.yqg.education.entity.OperateRecord;
import com.yqg.education.entity.User;
import com.yqg.education.entity.UserRole;
import com.yqg.education.mapper.UserMapper;
import com.yqg.education.service.IClassStudentService;
import com.yqg.education.service.IOperateRecordService;
import com.yqg.education.service.IUserRoleService;
import com.yqg.education.service.IUserService;
import com.yqg.education.utils.Constants;
import com.yqg.education.utils.IPUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * UserController 前端控制器
 *
 * @author zxf
 * @since 2025-03-01
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private IUserService userService;

    @Autowired
    IPUtils ipUtils;

    @Resource
    private UserMapper userMapper;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IOperateRecordService operateRecordService;

    @Autowired
    private IClassStudentService classStudentService;

    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody UserDTO userDTO) {
        String telephone = userDTO.getTelephone();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(telephone) || StrUtil.isBlank(password)) {
            return Result.error(Constants.String_CODE_400, "参数错误");
        }
        UserDTO dto = userService.login(userDTO);
//        OperateRecord operateRecord = new OperateRecord();
//        operateRecord.setUserId(userDTO.getId().longValue());
//        operateRecord.setIsDelete(0);
//        operateRecord.setOperateType("com.yqg.education.controller.UserController.login()");
//        operateRecord.setContent("用户登录");
//        operateRecord.setUserIp(ipUtils.getIpAddr(request));
//        operateRecord.setCreatedTime(LocalDateTime.now());
//        operateRecordService.save(operateRecord);
        return Result.success(dto);
    }

    /**
     * 新增或者更新
     */
    @PostMapping("/edit")
//    @SysLog("新增或者更新用户")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@RequestBody User user) {
        if (ObjectUtil.isEmpty(user.getId())) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getTelephone, user.getTelephone());
            queryWrapper.eq(User::getIsDelete, 0);
            User one = userService.getOne(queryWrapper);
            if (one != null) {
                return Result.error("手机号已存在");
            }
            user.setPassword(SecureUtil.md5("123456"));
            user.setCreateTime(LocalDateTime.now());
            user.setIsDelete(0);
            userService.saveOrUpdate(user);
            ArrayList<UserRole> userRoles = new ArrayList<>();
            List<Long> roleIds = user.getRoleIds();
            if (user.getClassId() != null && !user.getClassId().equals("")) {
                ClassStudent classStudent = new ClassStudent();
                classStudent.setClassId(user.getClassId().longValue());
                classStudent.setStuId(user.getId());
                classStudentService.save(classStudent);
            }
            for (Long roleId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setUserId(user.getId());
                userRole.setRoleId(roleId);
                userRoles.add(userRole);
            }
            return Result.success(userRoleService.saveBatch(userRoles));
        } else {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getTelephone, user.getTelephone());
            queryWrapper.eq(User::getIsDelete, 0);
            User one = userService.getOne(queryWrapper);
            if (one != null && !one.getId().equals(user.getId())) {
                return Result.error("手机号已存在");
            }
            user.setUpdateTime(LocalDateTime.now());
            userService.saveOrUpdate(user);
            if (user.getClassId() != null && !user.getClassId().equals("")) {
                LambdaQueryWrapper<ClassStudent> classStudentQueryWrapper = new LambdaQueryWrapper<>();
                classStudentQueryWrapper.eq(ClassStudent::getStuId, user.getId());
                ClassStudent classStudent = classStudentService.getOne(classStudentQueryWrapper);
                if (classStudent == null) {
                    classStudent = new ClassStudent();
                    classStudent.setStuId(user.getId());
                }
                classStudent.setClassId(user.getClassId().longValue());
                classStudentService.saveOrUpdate(classStudent);
            } else {
                LambdaQueryWrapper<ClassStudent> classStudentQueryWrapper = new LambdaQueryWrapper<>();
                classStudentQueryWrapper.eq(ClassStudent::getId, user.getId());
                classStudentService.remove(classStudentQueryWrapper);
            }
            user.getRoleIds().add(user.getId());
            return Result.success(userRoleService.updateUserRole(user.getRoleIds()));
        }
    }

    /**
     * 删除
     */
    @GetMapping("delete/{id}")
//    @SysLog("删除用户")
    @Transactional(rollbackFor = Exception.class)
    public Result delete(@PathVariable Integer id) {
        User user = userService.getById(id);
        user.setIsDelete(1);
        userService.saveOrUpdate(user);
        LambdaQueryWrapper<ClassStudent> classStuQueryWrapper = new LambdaQueryWrapper<>();
        classStuQueryWrapper.eq(ClassStudent::getStuId, user.getId());
        classStudentService.remove(classStuQueryWrapper);
        LambdaQueryWrapper<UserRole> userRoleWrapper = new LambdaQueryWrapper<>();
        userRoleWrapper.eq(UserRole::getUserId, id);
        return Result.success(userRoleService.remove(userRoleWrapper));
    }

    /**
     * 查询所有
     */
    @GetMapping("/all")
    public Result findAll() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        List<User> list = userService.list(queryWrapper);
        return Result.success(list);
    }

    /**
     * 根据id查询
     */
    @PostMapping("/getinfo")
    public Result getinfo(HttpServletRequest request,
                          @RequestParam(required = false, defaultValue = "0") String flag) {
        return Result.success(userService.getUserInfo(request,flag));
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           String name,
                           String telephone,
                           Integer roleId,
                           @RequestParam(required = false) Integer classId) {
        pageNum = pageNum * pageSize - pageSize;
        List<User> userList = userMapper.findPage(pageNum, pageSize, name, telephone, roleId, classId);
        Long count = userMapper.findCount(name, telephone, roleId, classId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("records", userList);
        map.put("total", count);
        return Result.success(map);
    }

    /**
     * 重置用户密码
     */
    @GetMapping("resetPwd")
//    @SysLog("重置用户密码")
    public Result resetPwd(int id) {
        userService.resetPwd(id, SecureUtil.md5("123456"), new Date());
        return Result.success(true);
    }

    /**
     * 修改密码
     */
    @PostMapping("/password")
//    @SysLog("修改用户密码")
    public Result password(@RequestBody UserPasswordDTO userPasswordDTO) {
        userPasswordDTO.setPassword(SecureUtil.md5(userPasswordDTO.getPassword()));
        userPasswordDTO.setNewPass(SecureUtil.md5(userPasswordDTO.getNewPass()));
        userService.updatePassword(userPasswordDTO);
        return Result.success();
    }

    @GetMapping("/selectTeachers")
    public Result selectTeachers() {
        List<User> list = userMapper.selectTeachers();
        return Result.success(list);
    }

    @GetMapping("/selectManages")
    public Result selectManages() {
        List<User> list = userMapper.selectManages();
        return Result.success(list);
    }

    /**
     * 学员端更改学员的个人信息
     */
    @PostMapping("/stuUpdateUserInfo")
    public Result stuUpdateUserInfo(@RequestBody StuDTO stuDTO) {
        LambdaQueryWrapper<User> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(User::getId, stuDTO.getId());
        User user = new User();
        user.setUsername(stuDTO.getUsername());
        user.setAge(stuDTO.getAge());
        user.setSex(stuDTO.getSex());
        user.setPhoto(stuDTO.getPhoto());
        user.setTelephone(stuDTO.getTelephone());
        user.setUnit(stuDTO.getUnit());
        user.setDepartment(stuDTO.getDepartment());
        user.setSection(stuDTO.getSection());
        user.setEmail(stuDTO.getEmail());
        userService.update(user, updateWrapper);
        return Result.success();
    }

    /**
     * 学员端查询个人信息
     */
    @GetMapping("/stuFindUserInfo")
    public Result stuUpdateUserInfo(@RequestParam Integer stuId) {
        User user = userMapper.stuFindUserInfo(stuId);
        return Result.success(user);
    }


    @ApiOperation("导入数据")
    @PostMapping("/importData")
    @Transactional(rollbackFor = Exception.class)
    public void importData(MultipartFile file) {
        userService.importData(file);
    }

    @ApiOperation("导出学生数据")
    @GetMapping("/export")
    public void exportStu(HttpServletResponse response,
                          String name,
                          String telephone,
                          Integer roleId,
                          @RequestParam(required = false) Integer classId) {
        userService.exportStu(response, name, telephone, roleId, classId);
    }
}

